package com.ooqiu.gaming.ui.web;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.base.BaseShareActivity;
import com.ooqiu.gaming.common.Constants;
import com.ooqiu.gaming.components.storage.UserStorage;
import com.ooqiu.gaming.ui.article_detail.AndroidBridge;
import com.ooqiu.gaming.utils.LogUtil;
import com.ooqiu.gaming.view.Topbar;
import com.tencent.smtt.sdk.WebBackForwardList;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.umeng.socialize.UMShareAPI;

import java.net.URLDecoder;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

@Route(path = WebActivity.PATH)
public class WebActivity extends BaseShareActivity implements View.OnLongClickListener{

    public static final String PATH = "/gn/web";
    @BindView(R.id.topbar)
    Topbar mTopbar;
    @BindView(R.id.web_x5)
    X5WebView mWebX5;

    @Autowired(name = "url", required = true)
    String mUrl;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;

    UserStorage mUserStorage;



    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            LogUtil.e("getAction = " + intent.getAction());

            if (intent.getAction().equals(Constants.ACTION_LOGIN_STATE_CHANGE)) {
                mWebX5.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        LogUtil.e(mWebX5.getUrl());
                        mWebX5.reload();
                    }
                }, 2000);
            }


            if (intent.getAction().equals(Constants.ACTION_PAY_STATE_CHANGE)) {

                Bundle bundle = intent.getBundleExtra("extra");

                boolean payRes = bundle.getBoolean("pay_res", false);


                String error_url = "http://www.ooqiuimg.com/alipay_return.php?total_amount=1&out_trade_no=2018011215527";
                String success_url = "http://www.ooqiuimg.com/alipay_return.php?total_amount=1&out_trade_no=2018011215527";


                LogUtil.e("%s\n%s\n%s", payRes, error_url, success_url);

                if (payRes) {
                    if (!TextUtils.isEmpty(success_url)) {
                        mWebX5.loadUrl(success_url);
                    }
                } else {
                    if (!TextUtils.isEmpty(error_url)) {
                        mWebX5.loadUrl(error_url);
                    }
                }
            }
        }
    };


    public static void start(String url) {
        ARouter.getInstance().build(WebActivity.PATH)
                .withString("url", url)
                .navigation();
    }

    @Override
    public int initContentView() {
        return R.layout.activity_web;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);


    }

    @Override
    public void initInjector() {
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);

        mUserStorage = getApplicationComponent().getUserStorage();
        mUrl = URLDecoder.decode(mUrl);
        LogUtil.e(mUrl);





//        if (!TextUtils.isEmpty(mUrl)) {
//            Uri.Builder builder = Uri.parse(mUrl).buildUpon().appendQueryParameter("platform", "android");
//            if (mUserStorage.isLogin()) {
//                builder.appendQueryParameter("token", mUserStorage.getToken());
//            }
//            mUrl = builder.toString();
//        }


    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);

    }

    @Override
    public void initUiAndListener() {
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                ArrayList<View> outView = new ArrayList<>();
                getWindow().getDecorView().findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT);
                int size = outView.size();
                if (outView != null && outView.size() > 0) {
                    outView.get(0).setVisibility(View.GONE);
                }
            }
        });


        mTopbar.setOnMenuClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WebBackForwardList mWebBackForwardList = mWebX5.copyBackForwardList();
                for (int i = 0; i < mWebBackForwardList.getSize(); i++) {
                    LogUtil.e("堆栈" + mWebBackForwardList.getItemAtIndex(i).getUrl());
                }

            }
        });


//        mWebX5.setOnLongClickListener(this);

        IntentFilter filter = new IntentFilter(Constants.ACTION_LOGIN_STATE_CHANGE);
        filter.addAction(Constants.ACTION_PAY_STATE_CHANGE);

        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, filter);

        mWebX5.loadUrl(mUrl);
        mWebX5.addJavascriptInterface(new AndroidBridge(this), "AndroidBridge");
        mWebX5.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int progress) {
                if (progress == 100) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.GONE == mProgressBar.getVisibility()) {
                        mProgressBar.setVisibility(View.VISIBLE);
                    }
                    mProgressBar.setProgress(progress);
                }
                super.onProgressChanged(webView, progress);
            }

        });
    }


    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @Override
    protected Toolbar toolbarIdRes() {
        return mTopbar;
    }


    @Override
    public void onBackPressed() {

        if (mWebX5.canGoBack()) {
//            WebBackForwardList webBackForwardList = mWebX5.copyBackForwardList();
//            int size = webBackForwardList.getSize();
//            String url = webBackForwardList.getItemAtIndex(size - 1).getUrl();
//            LogUtil.e("跳转URL = " + url);
//
//
//
//            if (url.contains("wx.tenpay.com") || url.contains("mclient.alipay.com")) {
//                LogUtil.e("存在重定向 = " + url + "\n加载别的url = " + webBackForwardList.getItemAtIndex(size - 2).getUrl());
//
//                mWebX5.loadUrl(webBackForwardList.getItemAtIndex(size - 2).getUrl());
//            } else {
//                LogUtil.e("不存在重定向 = " + url);
            mWebX5.goBack();
//            }


        } else {
            super.onBackPressed();
        }
    }


    @Override
    protected View statusLayoutId() {
        return null;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onLongClick(View v) {

        final WebView.HitTestResult htr = mWebX5.getHitTestResult();//获取所点击的内容
        LogUtil.e("type = " + htr.getType() + "   extra = " + htr.getExtra());
        return true;
    }


}
